﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yuebon.Extensions.Middlewares
{
    public static class HttpContextExtension
    {
        public static string GetClientIpAddress(this HttpContext context)
        {
            // 尝试从标准头获取
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();

            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Request.Headers["X-Real-IP"].FirstOrDefault();
            }

            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress?.ToString();
            }

            // 处理可能有多个IP的情况（如X-Forwarded-For: client, proxy1, proxy2）
            if (!string.IsNullOrEmpty(ip) && ip.Contains(','))
            {
                ip = ip.Split(',')[0].Trim();
            }

            // 处理本地地址情况
            if (string.IsNullOrEmpty(ip) || ip == "::1")
            {
                ip = "127.0.0.1";
            }

            return ip;
        }
    }
}
